<template>
    <div class="batch-upload" >
        <!-- 未上传状态 -->
        <div class="upload-container" v-if="!fileList.length" @drop.prevent="handleDrop" @dragover.prevent="handleDragOver" @dragleave.prevent="handleDragLeave" :class="{ dragging: isDragging }">
            <div class="uploadTopOut">
                <div class="uploadTop flex">
                    <button class="select-files-btn" @click="triggerFileInput">+ {{ t('BatchUpload.SelectFiles') }}</button>
                    <span class="or-text">{{ t('BatchUpload.OrDragDrop') }}</span>
                </div>
            </div>
        </div>

        <!-- 已上传状态 -->
        <div v-else class="batchContainer flex">
            <div class="batchLeftBox">
                <div class="Header flex">
                    <span class="title">{{ t('BatchUpload.Title') }}</span>
                    <div class="btnGroups flex">
                        <div class="btnBox flex" @click="showHistory = !showHistory">
                            <img src="@/assets/batchUpload/history.png" alt="" />
                            {{ t('BatchUpload.History') }}
                        </div>
                        <div class="btnBox flex" :class="{'disabled':loadingVisible}" @click="createMultiTask">
                            <img src="@/assets/batchUpload/play.png" alt="" />
                            {{ t('BatchUpload.StartProcess') }}
                        </div>
                    </div>
                </div>
                <div class="toolBox flex">
                    <span class="total">{{ t('BatchUpload.Total', { count: files.length }) }}</span>
                    <div class="toolItem flex" @click="triggerFileInput">
                        <img src="@/assets/batchUpload/add.png" alt="" />
                        {{ t('BatchUpload.Add') }}
                    </div>
                    <div class="toolItem flex" @click="clearAll">
                        <img src="@/assets/batchUpload/delete.png" alt="" />
                        {{ t('BatchUpload.ClearAll') }}
                    </div>
                    <!-- <div class="toolItem flex">
                        <label class="switch">
                            <input type="checkbox" v-model="useTextTool" />
                            <span class="slider"></span>
                        </label>
                        <span>{{ t('BatchUpload.UseTextTool') }}</span>
                    </div>
                    <div class="toolItem flex">
                        <label class="switch">
                            <input type="checkbox" v-model="useTextTool" />
                            <span class="slider"></span>
                        </label>
                        <span>{{ t('BatchUpload.KeepOriginalName') }}</span>
                    </div> -->

                    <div class="toolItem flex shengyu">
                        <!-- {{ t('BatchUpload.FreeCount', { count: freeCount }) }} -->
                    </div>
                </div>
                <div class="imageList" v-if="showHistory" v-loading="loadingVisible" element-loading-text="处理中" element-loading-background="rgba(0, 0, 0, 0.2)">
                    <div class="imageItem flex" v-for="(file, index) in fileList" :key="index" @click="showPreview(file)">
                        <div class="imageItemContainer flex">
                            <img :src="file.downloadUrl" :alt="file.name" class="previewImg" />
                            <div class="item-info">
                                <div class="name">{{ handleName(file.originFileName) }}</div>
                                <!-- <div class="size">{{ file.dimensions }}</div> -->
                            </div>
                        </div>
                        <div class="statusBox status1" v-if="file.status === 3">{{ t('BatchUpload.Status.Ready') }}</div>
                        <div class="statusBox status4" v-if="file.status === 4 || file.status === 2">{{ t('BatchUpload.Status.Processing') }}</div>
                        <div class="statusBox status3" v-if="file.status === 1">{{ t('BatchUpload.Status.Completed') }}</div>
                        <div class="statusBox status9" v-if="file.status === -9">{{ t('BatchUpload.Status.Failed') }}</div>
                        <div class="btnGroups flex">
                            <div class="btnBox flex" @click="downloadFile(file.downloadUrl, file.originFileName)" v-if="file.status == 1">
                                <img src="@/assets/batchUpload/download.png" alt="" />
                            </div>
                            <div class="btnBox flex" @click="removeAndClose(file.id)" v-if="file.status != 1">
                                <img src="@/assets/batchUpload/close.png" alt="" />
                            </div>
                        </div>
                    </div>
                </div>
                <div class="imageList" v-infinite-scroll="loadMore" :infinite-scroll-disabled="loading" v-show="!showHistory">
                    <div class="imageItem flex" v-for="(file, index) in historyList" :key="index" @click="showPreview(file)">
                        <div class="imageItemContainer flex">
                            <img :src="file.downloadUrl" :alt="file.name" class="previewImg" v-if="file.downloadUrl"/>
                            <div class="previewImg flex" v-else style="background-color: #efefef;">
                                {{ t('BatchUpload.Preview.NoImage') }}
                            </div>
                            <div class="item-info">
                                <div class="name">{{ handleName(file.originFileName) }}</div>
                                <div class="size">{{ file.dimensions }}</div>
                            </div>
                        </div>
                        <div class="statusBox status1" v-if="file.status === 3">{{ t('BatchUpload.Status.Ready') }}</div>
                        <div class="statusBox status4" v-if="file.status === 4 || file.status === 2">{{ t('BatchUpload.Status.Processing') }}</div>
                        <div class="statusBox status3" v-if="file.status === 1">{{ t('BatchUpload.Status.Completed') }}</div>
                        <div class="statusBox status9" v-if="file.status === -9">{{ t('BatchUpload.Status.Failed') }}</div>
                        <div class="btnGroups flex">
                            <div class="btnBox flex" @click="downloadFile(file.downloadUrl, file.originFileName)" v-if="file.status == 1">
                                <img src="@/assets/batchUpload/download.png" alt="" />
                            </div>
                            <div class="btnBox flex" @click="removeAndClose(file.id)" v-if="file.status != 1">
                                <img src="@/assets/batchUpload/close.png" alt="" />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="batchRightBox">
                <div class="topTip">{{ t('BatchUpload.Preview.Tip') }}</div>
                <div class="preViewContainer flex" v-if="previewFile">
                    <p class="name">{{ handleName(previewFile.originFileName) }}</p>
                    <div class="size flex">
                        <!-- {{ previewFile.dimensions }} -->
                        <div class="statusBox status1" v-if="previewFile.status === 3">{{ t('BatchUpload.Status.Ready') }}</div>
                        <div class="statusBox status4" v-if="previewFile.status === 4">{{ t('BatchUpload.Status.Processing') }}</div>
                        <div class="statusBox status3" v-if="previewFile.status === 1">{{ t('BatchUpload.Status.Completed') }}</div>
                        <div class="statusBox status9" v-if="previewFile.status === -9">{{ t('BatchUpload.Status.Failed') }}</div>
                    </div>
                    <img :src="previewFile.downloadUrl" :alt="previewFile.name" class="previewImg" />
                </div>
                <div class="preViewContainer flex" v-else>
                    <img src="@/assets/photo_tv.svg" alt="" class="emptyImg" />
                    <p class="emptyText">{{ t('BatchUpload.Preview.SelectToPreview') }}</p>
                </div>
            </div>
        </div>

        <input type="file" ref="fileInput" multiple accept="image/*" style="display: none" @change="handleFileSelect" />
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { createTaskApi, createMultiTaskApi, getTaskListApi } from '@/api/payment'
import { downloadFile } from '@/utils/tools'
import { v4 as uuidv4 } from 'uuid'
import encrypt from '@/utils/encrypt.js'
const { t } = useI18n()
const fileInput = ref(null)
const files = ref([])
const useTextTool = ref(false)
const keepOriginalName = ref(true)
const freeCount = ref(0)
const previewFile = ref(null)
const previewIndex = ref(-1)
const route = useRoute()
const router = useRouter()
const isDragging = ref(false)
const fileList = ref([])
const historyList = ref([])
const loading = ref(false)
const loadingVisible = ref(false)
const loadFinish = ref(false)
const showHistory = ref(true)
const currentTask = ref('')
const timer = ref(null)
const pagination = ref({
    pageNo: 0,
    pageSize: 10,
    total: 0
})
const triggerFileInput = () => {
    fileInput.value.click()
}

const handleFileSelect = async event => {
    const selectedFiles = Array.from(event.target.files)
    for (const file of selectedFiles) {
        const dimensions = await getImageDimensions(file)
        let uid = uuidv4()
        files.value.unshift({
            file,
            id:uid,
            name: file.name,
            preview: URL.createObjectURL(file),
            dimensions: `${dimensions.width}x${dimensions.height}px`
        })

        fileList.value.unshift({
            downloadUrl:URL.createObjectURL(file),
            image:URL.createObjectURL(file),
            originFileName: file.name,
            status:3,
            id:uid,
            dimensions: `${dimensions.width}x${dimensions.height}px`
        })
    }
    event.target.value = '' // Reset input
}

const getImageDimensions = file => {
    return new Promise(resolve => {
        const img = new Image()
        img.onload = () => {
            resolve({ width: img.width, height: img.height })
        }
        img.src = URL.createObjectURL(file)
    })
}

const removeFile = id => {
    files.value.forEach((item,index) => {
        if(item.id === id){
            URL.revokeObjectURL(item.preview)
            files.value.splice(index, 1)
        }
    })
    files.value = files.value.filter(item => item.id != id)
    fileList.value = fileList.value.filter(item => item.id != id)

}

// 处理名字过长，取前五位后五位中间三省略
const handleName = (name) => {
    if(name.length > 10){
        return name.slice(0,5) + '...' + name.slice(-5)
    }
    return name
}


const clearAll = () => {
    files.value.forEach(file => {
        URL.revokeObjectURL(file.preview)
    })
    files.value.length = 0
    fileList.value = fileList.value.filter(item => item.status == 1)
}

const processAll = () => {
    console.log('Processing all files')
}

const showPreview = file => {
    previewFile.value = file
    previewIndex.value = files.value.findIndex(f => f === file)
}

const closePreview = () => {
    previewFile.value = null
    previewIndex.value = -1
}

const removeAndClose = index => {
    removeFile(index)
    closePreview()
}

const handleDragOver = e => {
    isDragging.value = true
    e.dataTransfer.dropEffect = 'copy'
}

const handleDragLeave = () => {
    isDragging.value = false
}

const handleDrop = async e => {
    isDragging.value = false
    const droppedFiles = Array.from(e.dataTransfer.files).filter(file => file.type.startsWith('image/'))
    console.log(droppedFiles,'droppedFiles');

    if (droppedFiles.length === 0) {
        // 可以添加提示：只能上传图片文件
        return
    }

    for (const file of droppedFiles) {
        const dimensions = await getImageDimensions(file)
        let uid = uuidv4()
        files.value.unshift({
            file,
            id:uid,
            name: file.name,
            preview: URL.createObjectURL(file),
            dimensions: `${dimensions.width}x${dimensions.height}px`
        })

        fileList.value.unshift({
            downloadUrl: URL.createObjectURL(file),
            image:URL.createObjectURL(file),
            id:uid,
            originFileName: file.name,
            status:3,
            dimensions: `${dimensions.width}x${dimensions.height}px`
        })
    }
}


/** 创建多任务 */
const createMultiTask = async () => {
    if(loadingVisible.value){
        return
    }
    currentTask.value = uuidv4()
    // 检查用户是否已登录
    const token = encrypt.GetLocalData('accessToken')
    if (!token) {
        ElMessage.error(t('BatchUpload.Messages.LoginFirst'))
        router.push('/login')
        return
    }
    if(timer.value){
       return
    }
    loadingVisible.value = true
    let fdata = []
    files.value.forEach(file => {
        fdata.push({[`${currentTask.value}|${file.id}`]:file.file})
    })
    fileList.value.forEach(item => {
        item.status = 4
    })
    try {
        let res = await createMultiTaskApi(fdata)
        if(res.code === 200){
            ElMessage.success(t('BatchUpload.Messages.CreateSuccess'))
            pagination.value.pageNo = 0
            timer.value = setInterval(() => {
                getTaskList(true,currentTask.value)
            }, 1000)
            loadingVisible.value = false
        }else{
            ElMessage.error(t('BatchUpload.Messages.CreateFailed'))
            loadingVisible.value = false
        }
    } catch (error) {
        loadingVisible.value = false
    }
}


const loadMore = async () => {
    if(loadFinish.value){
        return
    }
    loading.value = true
    pagination.value.pageNo++
    await getHistoryList()
    loading.value = false
}

/** 获取任务列表 */
const getTaskList = async (bool = false,uuid = '') => {
    let res = await getTaskListApi({
        pageNo: 0,
        pageSize: files.value.length,
        uuid: uuid
    })
    res.data.records.forEach(item => {
        item.dimensions = ''
        item.downloadUrl = item.downloadUrl
        item.uid = item.image?.split("[")[1]?.split("]")[0]
    })
    if(res.data.records.length === 0){
        loadFinish.value = true
    }
    let finishData = res.data.records.filter(item => item.status == 0)
    // 如果所有任务都已完成，则停止定时器
    if(finishData.length == 0){
        clearInterval(timer.value)
        timer.value = null
    }
    fileList.value.forEach(item => {
        res.data.records.forEach(item2 => {
        if(item2.uid == item.id){
            item.downloadUrl = item2.downloadUrl ? item2.downloadUrl : item.downloadUrl
            item.status = item2.status
        }
       })
    })
    pagination.value.total = res.data.total;
}

const getHistoryList = async (bool = false) => {
    let res = await getTaskListApi({
        pageNo: pagination.value.pageNo,
        pageSize: 10
    })
    historyList.value.push(...res.data.records)
}

onMounted(() => {
    const filesData = JSON.parse(localStorage.getItem('files'))
    getHistoryList()
    if (filesData) {
        files.value.unshift(...filesData)
        localStorage.removeItem('files')
    }
})
</script>

<style lang="scss" scoped>
.batch-upload {
    display: flex;
    flex-direction: column;
    height: calc(100% - 2px);
    background: #fff;
    margin-top: 2px;

    // 上传区域样式
    .upload-container {
        width: 100%;
        height: 100%;
        padding: 20px;
        box-sizing: border-box;
        transition: all 0.3s ease;

        &.dragging {
            .uploadTopOut {
                border-color: #ff5722;
                background: rgba(255, 87, 34, 0.05);
            }
        }

        .uploadTopOut {
            width: 100%;
            height: 100%;
            border: 2px dashed #ddd;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;

            &:hover {
                border-color: #ff5722;
            }

            .uploadTop {
                flex-direction: column;
                gap: 15px;

                .select-files-btn {
                    background: #ff5722;
                    color: white;
                    border: none;
                    padding: 12px 30px;
                    border-radius: 4px;
                    font-size: 18px;
                    cursor: pointer;
                }

                .or-text {
                    color: #666;
                    font-size: 16px;
                }
            }
        }
    }

    .batchContainer {
        width: 100%;
        height: 100%;

        .batchLeftBox {
            width: 70%;
            height: 100%;
            padding: 20px;
            box-sizing: border-box;
            color: #000;
            padding-bottom: 50px;

            .Header {
                width: 100%;
                height: 50px;
                justify-content: space-between;

                .title {
                    font-size: 32px;
                    font-weight: bold;
                }

                .btnGroups {
                    gap: 20px;

                    .btnBox {
                        gap: 10px;
                        color: #fff;
                        border-radius: 8px;
                        padding: 12px 18px;
                        background-color: #f85521;
                        font-weight: 600;
                        cursor: pointer;

                        img {
                            width: 18px;
                            height: 18px;
                        }
                    }

                    .disabled{
                        cursor: not-allowed;
                        background-color: #a78d84;
                    }
                }
            }

            .toolBox {
                position: relative;
                width: 100%;
                height: 70px;
                justify-content: flex-start;
                gap: 35px;

                .total {
                    font-size: 18px;
                    font-weight: bold;
                }

                .toolItem {
                    gap: 8px;
                    font-weight: 600;
                    cursor: pointer;

                    img {
                        width: 20px;
                        height: 20px;
                    }
                }

                .shengyu {
                    position: absolute;
                    right: 0px;
                }
            }

            .imageList {
                width: 100%;
                height: calc(100% - 150px);
                overflow-y: auto;

                .imageItem {
                    position: relative;
                    width: 100%;
                    height: 150px;
                    border-bottom: 1px solid #efefef;
                    padding: 15px;
                    box-sizing: border-box;
                    justify-content: flex-start;
                    gap: 20px;

                    .imageItemContainer {
                        height: 100%;
                        gap: 20px;
                    }

                    &:hover {
                        cursor: pointer;
                        background: #efefef;
                    }

                    .previewImg {
                        aspect-ratio: 1 / 1;
                        height: 100%;
                        object-fit: contain;
                    }

                    .item-info {
                        .name {
                            font-weight: 600;
                            margin-bottom: 14px;
                        }

                        .size {
                            color: #333333;
                            font-size: 17px;
                        }
                    }

                    .statusBox {
                        position: absolute;
                        right: 30%;
                    }

                    .btnGroups {
                        position: absolute;
                        right: 20px;
                        gap: 20px;

                        .btnBox {
                            padding: 10px 20px;
                            border-radius: 10px;
                            cursor: pointer;

                            img {
                                width: 20px;
                                height: 20px;
                            }
                        }

                        .btnBox:first-child {
                            background-color: #d6d6d6;
                        }
                    }
                }
            }
        }

        .batchRightBox {
            width: 30%;
            height: 100%;
            color: #000;
            padding: 20px;
            box-sizing: border-box;
            border-left: 1px solid #efefef;

            .topTip {
                width: 100%;
                border-radius: 6px;
                padding: 6px;
                box-sizing: border-box;
                font-size: 14px;
                background-color: #efefef;
            }

            .preViewContainer {
                width: 100%;
                height: calc(100% - 50px);
                flex-direction: column;
                transform: translateY(-100px);

                .name {
                    font-size: 16px;
                    font-weight: bold;
                }

                .size {
                    font-size: 18px;
                    color: #696969;
                    margin: 8px 15px;
                    gap: 8px;
                }

                .previewImg {
                    width: 40%;
                    aspect-ratio: 1 / 1;
                    object-fit: contain;
                    margin: 20px 0 50px;
                }

                .emptyImg {
                    width: 82px;
                    height: 82px;
                }

                .emptyText {
                    margin-top: 20px;
                }
            }
        }
    }
}

.statusBox {
    padding: 5px 10px;
    border-radius: 18px;
    font-size: 12px;
    font-weight: bold;
}

.status1 {
    background-color: #ebf2fe;
    color: #0051ee;
}

.status4 {
    background-color: #f85521;
    color: #fff;
}

.status3 {
    background-color: #c3f1dc;
    color: #048100;
}

.status9{
    background-color: #ff0000;
    color: #fff;
}

// Switch styles
.switch {
    position: relative;
    display: inline-block;
    width: 36px;
    height: 20px;

    input {
        opacity: 0;
        width: 0;
        height: 0;

        &:checked + .slider {
            background-color: #ff5722;
        }

        &:checked + .slider:before {
            transform: translateX(16px);
        }
    }

    .slider {
        position: absolute;
        cursor: pointer;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: #ddd;
        transition: 0.3s;
        border-radius: 20px;

        &:before {
            position: absolute;
            content: '';
            height: 16px;
            width: 16px;
            left: 2px;
            bottom: 2px;
            background-color: white;
            transition: 0.3s;
            border-radius: 50%;
        }
    }
}
</style>
